#include <p24FJ64GA102.h>
#include "TCPIP Stack/TCPIP.h"
#include "LED.h"
#include "IPParser.h"
#include "StringUtils.h"

#define IP_TO_PING "192.168.0.100"

static DWORD ipConvert(const char* ip);
static void processPingReply(LONG pingReply);

void pingApp(void) {
	int i;
	Leds.set(LED_ALL);

	while (!ICMPBeginUsage());

	Leds.set(LED_NONE);

	for(i = 0; i < 4; i++) {
		ICMPSendPing(ipConvert(IP_TO_PING));
		
		processPingReply(ICMPGetReply());
	}

	ICMPEndUsage();
}

static DWORD ipConvert(const char* ip) {
	IPOctets ipOctets;

	IPStringToOctets(ip, &ipOctets);

	return (ipOctets.first | (DWORD)ipOctets.second << 8 | (DWORD)ipOctets.third << 16 | (DWORD)ipOctets.fourth << 24);
}

static void processPingReply(LONG pingReply) {
	switch(pingReply) {
		case -3: //Could not resolve hostname (DNS timeout or hostname invalid)
			Leds.set(LED_1);
		break;
		case -2: //No response received yet
			Leds.set(LED_2);
		break;
		case -1: //Operation timed out
			Leds.set(LED_2);
		break;
		default: //Ok
			Leds.set(LED_3);
		break;
	}
}
